package com.hemh.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;

/**
 * @author HeMingHui
 * @since 2020-10-24
 * @description AES加密
 */
public class AESUtil {

	/** 密钥 */
    private static String sKey = "e3cc7538e94ce646";
	/** 偏移量(增加算法强度) */
    private static String ivParameter = "fa0c1c92739534cf";
	/** 公共参数 */
    private static String AES_ALGORITHM = "AES";
    private static String CODE_TYPE = "utf-8";
    private static String AES_TYPE = "AES/CBC/PKCS5Padding";

	/** 加密 */
	public static String encrypt(String sSrc) throws Exception {
		Cipher cipher = Cipher.getInstance(AES_TYPE);
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
		IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes(CODE_TYPE));
		// BASE64Encoder().encode(encrypted);
		return Base64.encodeBase64String(encrypted);/** 此处使用BASE64做转码 */
	}

	/** 解密 */
	public static String decrypt(String sSrc) throws Exception {
		try {
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
			Cipher cipher = Cipher.getInstance(AES_TYPE);
			IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			/** 先用base64解密 */
			// byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
			byte[] encrypted1 = Base64.decodeBase64(sSrc);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, CODE_TYPE);
			return originalString;
		} catch (Exception ex) {
			return null;
		}
	}

}
